package com.shanyi.common.util;

import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.dingtalkyida_1_0.models.GetFieldDefByUuidResponse;
import com.aliyun.dingtalkyida_1_0.models.GetFieldDefByUuidResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.shanyi.common.result.ding.DingOrgBaseReqDTO;
import com.shanyi.common.result.ding.YidaFormFieldsRespDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Map;

/**
 * @author shanyi
 * @create 2025-04-09-19:13
 */
@Slf4j
@Component
public class DingOrgUtil {
    public static Client createClient() throws Exception {
        Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new Client(config);
    }

    public static com.aliyun.dingtalkyida_1_0.Client createYidaClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkyida_1_0.Client(config);
    }

    public static com.aliyun.dingtalkyida_2_0.Client createYida2Client() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkyida_2_0.Client(config);
    }

    /**
     * 企业内应用获取accessToken
     *
     * @param appKey
     * @param appSecret
     * @return {@link String}
     */
    public String getAccessToken(String appKey, String appSecret) {
        String result = "";
        try {
            Client client = DingOrgUtil.createClient();
            GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest()
                    .setAppKey(appKey)
                    .setAppSecret(appSecret);
            GetAccessTokenResponse accessTokenResponse = client.getAccessToken(getAccessTokenRequest);
            result = accessTokenResponse.getBody().getAccessToken();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题

            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题

            }
        }
        log.info("获取钉钉宜搭accessToken成功!");
        return result;
    }

    /**
     * 获取表单组件信息
     *
     * @param dto
     * @param formUuid
     * @return {@link ArrayList}<{@link YidaFormFieldsRespDTO}>
     */
    public ArrayList<YidaFormFieldsRespDTO> getFormFields(DingOrgBaseReqDTO dto, String formUuid) {
        ArrayList<YidaFormFieldsRespDTO> list = new ArrayList<>();
        try {
            com.aliyun.dingtalkyida_1_0.Client yidaClient = DingOrgUtil.createYidaClient();
            com.aliyun.dingtalkyida_1_0.models.GetFieldDefByUuidHeaders getFieldDefByUuidHeaders = new com.aliyun.dingtalkyida_1_0.models.GetFieldDefByUuidHeaders();
            getFieldDefByUuidHeaders.xAcsDingtalkAccessToken = dto.getAccessToken();
            com.aliyun.dingtalkyida_1_0.models.GetFieldDefByUuidRequest getFieldDefByUuidRequest = new com.aliyun.dingtalkyida_1_0.models.GetFieldDefByUuidRequest()
                    .setAppType(dto.getAppType())
                    .setSystemToken(dto.getSystemToken())
                    .setFormUuid(formUuid)
                    .setUserId(dto.getUserId());
            GetFieldDefByUuidResponse response = yidaClient.getFieldDefByUuidWithOptions(getFieldDefByUuidRequest, getFieldDefByUuidHeaders, new RuntimeOptions());
            for (GetFieldDefByUuidResponseBody.GetFieldDefByUuidResponseBodyResult responseBodyResult : response.getBody().getResult()) {
                YidaFormFieldsRespDTO respDTO = new YidaFormFieldsRespDTO();
                respDTO.setFieldId(responseBodyResult.getFieldId());
                respDTO.setBehavior(responseBodyResult.getBehavior());
                respDTO.setChildren(responseBodyResult.getChildren());
                respDTO.setComponentName(responseBodyResult.getComponentName());
                respDTO.setLabel((Map) responseBodyResult.getLabel());
                list.add(respDTO);
            }

        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题

            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题

            }
        }
        return list;
    }

//    /**
//     * 批量删除
//     * @param dto
//     */
//    public void yidaBatchRemove(YidaBatchRemoveReqDTO dto) {
//        try {
//            com.aliyun.dingtalkyida_1_0.Client yidaClient = DingOrgUtil.createYidaClient();
//            BatchRemovalByFormInstanceIdListHeaders batchRemovalByFormInstanceIdListHeaders = new BatchRemovalByFormInstanceIdListHeaders();
//            batchRemovalByFormInstanceIdListHeaders.xAcsDingtalkAccessToken = dto.getAccessToken();
//            BatchRemovalByFormInstanceIdListRequest batchRemovalByFormInstanceIdListRequest = new BatchRemovalByFormInstanceIdListRequest()
//                    .setFormUuid(dto.getFormUuid())
//                    .setAppType(dto.getAppType())
//                    .setAsynchronousExecution(true)
//                    .setSystemToken(dto.getSystemToken())
//                    .setFormInstanceIdList(dto.getFormInstanceIdList())
//                    .setUserId(dto.getUserId())
//                    .setExecuteExpression(false);
//            yidaClient.batchRemovalByFormInstanceIdListWithOptions(batchRemovalByFormInstanceIdListRequest, batchRemovalByFormInstanceIdListHeaders, new RuntimeOptions());
//        } catch (TeaException err) {
//            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
//                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                throw new BizException("qymall.ding-org-batch-remove-error", err.getMessage());
//            }
//        } catch (Exception _err) {
//            TeaException err = new TeaException(_err.getMessage(), _err);
//            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
//                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                throw new BizException("qymall.ding-org-batch-remove-error", err.getMessage());
//            }
//        }
//    }
//
//    /**
//     * 批量插入
//     *
//     * @param dto
//     * @return {@link List}<{@link String}>
//     */
//    public List<String> yidaBatchSave(YidaBatchSaveReqDTO dto) {
//        ArrayList<String> result = new ArrayList<>();
//        try {
//            com.aliyun.dingtalkyida_1_0.Client yidaClient = DingOrgUtil.createYidaClient();
//            BatchSaveFormDataHeaders batchSaveFormDataHeaders = new BatchSaveFormDataHeaders();
//            batchSaveFormDataHeaders.xAcsDingtalkAccessToken = dto.getAccessToken();
//            BatchSaveFormDataRequest batchSaveFormDataRequest = new BatchSaveFormDataRequest()
//                    .setNoExecuteExpression(true)
//                    .setFormUuid(dto.getFormUuid())
//                    .setAppType(dto.getAppType())
//                    .setAsynchronousExecution(true)
//                    .setSystemToken(dto.getSystemToken())
//                    .setKeepRunningAfterException(true)
//                    .setUserId(dto.getUserId())
//                    .setFormDataJsonList(dto.getFormDataJsonList());
//            BatchSaveFormDataResponse response = yidaClient.batchSaveFormDataWithOptions(batchSaveFormDataRequest, batchSaveFormDataHeaders, new RuntimeOptions());
//            log.info("表单uuid{}的数据插入状态码是：{}",dto.getFormUuid(),response.getStatusCode());
//            result.addAll(response.getBody().getResult());
//        } catch (TeaException err) {
//            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
//                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                throw new BizException("qymall.ding-org-batch-save-error", err.getMessage());
//            }
//        } catch (Exception _err) {
//            TeaException err = new TeaException(_err.getMessage(), _err);
//            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
//                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                throw new BizException("qymall.ding-org-batch-save-error", err.getMessage());
//            }
//        }
//        result.forEach(t -> {
//            log.info("表单uuid{}的数据插入:{}成功！",dto.getFormUuid(), t);
//        });
//        return result;
//    }
//
//    /**
//     * 根据条件查询：只是获取某一页的数据
//     * @param dto
//     * @return {@link YidaQueryRespDTO}
//     */
//    public YidaQueryRespDTO query(YidaQueryReqDTO dto) {
//        YidaQueryRespDTO result = new YidaQueryRespDTO();
//        try {
//            com.aliyun.dingtalkyida_1_0.Client yidaClient = DingOrgUtil.createYidaClient();
//            SearchFormDataSecondGenerationNoTableFieldHeaders searchFormDataSecondGenerationNoTableFieldHeaders = new SearchFormDataSecondGenerationNoTableFieldHeaders();
//            searchFormDataSecondGenerationNoTableFieldHeaders.xAcsDingtalkAccessToken = dto.getAccessToken();
//            SearchFormDataSecondGenerationNoTableFieldRequest searchFormDataSecondGenerationNoTableFieldRequest = new SearchFormDataSecondGenerationNoTableFieldRequest()
//                    .setPageNumber(dto.getPageNumber())
//                    .setFormUuid(dto.getFormUuid())
//                    .setSearchCondition(dto.getSearchCondition())
//                    .setModifiedToTimeGMT(dto.getModifiedToTimeGMT())
//                    .setSystemToken(dto.getSystemToken())
//                    .setModifiedFromTimeGMT(dto.getModifiedFromTimeGMT())
//                    .setPageSize(dto.getPageSize())
//                    .setUserId(dto.getUserId())
//                    .setAppType(dto.getAppType())
//                    .setOrderConfigJson(dto.getOrderConfigJson())
//                    .setOriginatorId(dto.getUserId())
//                    .setCreateToTimeGMT(dto.getCreateToTimeGMT())
//                    .setCreateFromTimeGMT(dto.getCreateFromTimeGMT());
//            // 查询
//            SearchFormDataSecondGenerationNoTableFieldResponse response = yidaClient
//                    .searchFormDataSecondGenerationNoTableFieldWithOptions(
//                            searchFormDataSecondGenerationNoTableFieldRequest,
//                            searchFormDataSecondGenerationNoTableFieldHeaders,
//                            new RuntimeOptions());
//            SearchFormDataSecondGenerationNoTableFieldResponseBody responseBody = response.getBody();
//            result.setPageNumber(responseBody.getPageNumber());
//            result.setTotalCount(responseBody.getTotalCount());
//            // 获取实例列表
//            result.setFormInstanceIds(responseBody.getData().stream()
//                    .map(SearchFormDataSecondGenerationNoTableFieldResponseBody
//                            .SearchFormDataSecondGenerationNoTableFieldResponseBodyData::getFormInstanceId)
//                    .collect(Collectors.toList()));
//        } catch (TeaException err) {
//            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
//                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                throw new BizException("qymall.ding-org-query-error", err.getMessage());
//            }
//        } catch (Exception _err) {
//            TeaException err = new TeaException(_err.getMessage(), _err);
//            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
//                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                throw new BizException("qymall.ding-org-query-error", err.getMessage());
//            }
//        }
//        return result;
//    }
//
//    /**
//     * 获取宜搭表单列表信息；需要传入页码及数量
//     * @param dto dto
//     * @return {@link GetFormListInAppResponse }
//     */
//    public GetFormListInAppResponse getFormList(YidaFormListReqDTO dto) {
//        GetFormListInAppResponse result = new GetFormListInAppResponse();
//        try {
//            com.aliyun.dingtalkyida_1_0.Client client = DingOrgUtil.createYidaClient();
//            GetFormListInAppHeaders getFormListInAppHeaders = new GetFormListInAppHeaders();
//            getFormListInAppHeaders.xAcsDingtalkAccessToken = dto.getAccessToken();
//            GetFormListInAppRequest getFormListInAppRequest = new GetFormListInAppRequest()
//                    .setAppType(dto.getAppType())
//                    .setSystemToken(dto.getSystemToken())
//                    .setFormTypes("receipt,process")
//                    .setPageSize(dto.getPageSize())
//                    .setPageNumber(dto.getPageNumber())
//                    .setUserId(dto.getUserId());
//            GetFormListInAppResponse response = client.getFormListInAppWithOptions(getFormListInAppRequest, getFormListInAppHeaders, new RuntimeOptions());
//
//            result.setStatusCode(response.getStatusCode());
//            result.setBody(response.getBody());
//            result.setHeaders(response.getHeaders());
//        } catch (TeaException err) {
//            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
//                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                throw new BizException("qymall.ding-form-list-query-error", err.getMessage());
//            }
//
//        } catch (Exception _err) {
//            TeaException err = new TeaException(_err.getMessage(), _err);
//            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
//                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                throw new BizException("qymall.ding-form-list-query-error", err.getMessage());
//            }
//        }
//        return result;
//    }
//
//    /**
//     * 宜搭流程插入
//     * @param dto dto
//     */
//    public void saveYidaProcess(YidaProcessSaveReqDTO dto) {
//        try {
//            com.aliyun.dingtalkyida_2_0.Client yida2Client = DingOrgUtil.createYida2Client();
//            com.aliyun.dingtalkyida_2_0.models.StartInstanceHeaders startInstanceHeaders = new com.aliyun.dingtalkyida_2_0.models.StartInstanceHeaders();
//            startInstanceHeaders.xAcsDingtalkAccessToken = dto.getAccessToken();
//            com.aliyun.dingtalkyida_2_0.models.StartInstanceRequest startInstanceRequest = new com.aliyun.dingtalkyida_2_0.models.StartInstanceRequest()
//                    .setAppType(dto.getAppType())
//                    .setSystemToken(dto.getSystemToken())
//                    .setUserId(dto.getUserId())
//                    .setLanguage("zh_CN")
//                    .setFormUuid(dto.getFormUuid())
//                    .setFormDataJson(dto.getFormDataJson())
//                    .setProcessCode(dto.getProcessCode());
//            StartInstanceResponse startInstanceResponse = yida2Client.startInstanceWithOptions(startInstanceRequest, startInstanceHeaders, new RuntimeOptions());
//            log.info("表单:{}宜搭流程插入状态:{}", dto.getFormUuid(), startInstanceResponse.getStatusCode());
//        } catch (TeaException err) {
//            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
//                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                throw new BizException("qymall.ding-process-error", err.getMessage());
//            }
//        } catch (Exception _err) {
//            TeaException err = new TeaException(_err.getMessage(), _err);
//            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
//                // err 中含有 code 和 message 属性，可帮助开发定位问题
//                throw new BizException("qymall.ding-process-error", err.getMessage());
//            }
//        }
//    }
}
